//
//  XJAfterSaleViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/19.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJAfterSaleViewController.h"

//view
#import "XJAfterSaleHeaderView.h"
#import "XJAfterSaleFooterView.h"
#import "XJLabelTextField.h"

//model
#import "XJAfterSaleModel.h"

@interface XJAfterSaleViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate>


/**tableVieq*/
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) XJAfterSaleHeaderView *headerView;
@property(nonatomic, strong) XJAfterSaleFooterView *footerView;
@property(nonatomic, strong) UIImagePickerController *pickerVC; //选择图片vc
@property(nonatomic, strong) XJAfterSaleModel *afterSaleModel;


@end

@implementation XJAfterSaleViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
    }
    return _tableView;
}

- (UIImagePickerController *)pickerVC {
    if (!_pickerVC) {
        _pickerVC = [[UIImagePickerController alloc] init];
        _pickerVC.delegate = self;
        _pickerVC.allowsEditing = YES;
    }
    return _pickerVC;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self reqeustHeaderDeatilInfo];
    
    
    self.tableView.frame = CGRectMake(0, 0, KWidth, KHeight - kStatusBarAndNavigationBarHeight);
    
    [self.view addSubview:self.tableView];
    
    self.headerView = [[XJAfterSaleHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 200)];
 
    self.footerView = [[XJAfterSaleFooterView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 400)];
     self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    
    XJWeakSelf(self);
    self.footerView.addImageBlock = ^{
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请选择上传方式" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照上传" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [weakself paiZhao];
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [weakself chooseFromAlbum];
        }];
    
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        
        [alertVC addAction:action1];
        [alertVC addAction:action2];
        [alertVC addAction:cancelAction];

        [weakself presentViewController:alertVC animated:YES completion:nil];
    };
    
    
    self.footerView.clickSubmitButtonBlock = ^{
       // 处理业务提交问题的业务逻辑
        [weakself businessLogicalOfSubmitButton];
    };
}

#pragma mark - Private method
- (void)paiZhao {
    XJLog(@"拍照");
    self.pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:self.pickerVC animated:YES completion:nil];
}
- (void)chooseFromAlbum {
    XJLog(@"从相册中选择");
    
    self.pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.pickerVC.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.pickerVC.sourceType];

    [self presentViewController:self.pickerVC animated:YES completion:nil];
}

//选择照片的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//    XJLog(@"%@",info);

    UIImage *selectedImage = info[UIImagePickerControllerEditedImage];
    
    [self.footerView.imageArray addObject:selectedImage];
    [self.footerView afterSaleReloadData];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//取消照片的回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)businessLogicalOfSubmitButton {
    [self.view endEditing:YES];
    
    if ([NSString isEmptyString:self.headerView.textView.text]) {
        [JRToast showWithText:@"问题描述不能为空"];
        return;
    }
    if ([NSString isEmptyString:self.footerView.nameTextField.text]) {
        [JRToast showWithText:@"联系人不能为空"];
        return;
    }
    if ([NSString isEmptyString:self.footerView.phoneTextField.text]) {
        [JRToast showWithText:@"联电话不能为空"];
        return;
    }
    if (![self.footerView.phoneTextField.text isPhoneNumber]) {
        [JRToast showWithText:@"请输入正确的手机号"];
        return;
    }
    
    // 调用接口
    [self requestCommit];
        
}

#pragma mark - 网路请求
- (void)reqeustHeaderDeatilInfo {
    
    if ([NSString isEmptyString:self.order_goods_id]) {
        XJLog(@"self.order_goods_id为空");
        return;
    }
    
    [XJHttpTool requestOrderOrderPageWithOrderGoodsId:self.order_goods_id successH:^(id responseObjc) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        XJLog(@"%@",jsonStr);
        
        NSArray *tempArr = responseObjc[@"data"][@"order_goods"];
        NSDictionary *tempDic =  [tempArr firstObject];
        self.afterSaleModel = [XJAfterSaleModel mj_objectWithKeyValues:tempDic];
        
    } failH:^(NSError *error) {
        
        [JRToast showWithText:[error localizedDescription]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.headerView.afterM = self.afterSaleModel;
        });
    }];
}

- (void)requestCommit {
    if ([NSString isEmptyString:self.orderSN]) {
        XJLog(@"self.orderSN 为空 操作无效");
        return;
    }
    
    
    //请求参数
    //问题描述
    NSString *descStr = self.headerView.textView.text;
    if ([NSString isEmptyString:descStr]) {
        descStr = @"";
    }
    //联系人姓名
    NSString *linkman = self.footerView.nameTextField.text;
    //联系人电话
    NSString *phone = self.footerView.phoneTextField.text;
    
    NSDictionary *parDic = @{@"order_sn":self.orderSN,
                             @"refund":@{@"order_goods_id":self.afterSaleModel.orderGoodsID,
                                         @"images":@"",
                                         @"linkman":linkman,
                                         @"phone":phone,
                                         @"reason":descStr
                                         }
                             };
    
    [XJHttpTool requestRefundCommitRefundWithDic:parDic successH:^(id responseObjc) {
        
        XJLog(@"%@",responseObjc);
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            [JRToast showWithText:@"申请售后成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        
        [JRToast showWithText:[error localizedDescription]];
    }];
    
}



//#pragma mark UIGestureRecognizerDelegate 回收键盘
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//
//    [self.tableView endEditing:YES];
//
//    //若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
//    if([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
//        return NO;
//    }
//    return YES;
//}




@end
